<template>
    <div>
        <!-- 头部 -->
        <div id="headdiv">
            <span>单位列表</span>
            <div id="sale">
                <el-button class="add-button" @click="UnitAddModal">新增计量单位</el-button>
            </div>
        </div>
        
        <!-- 下划线分隔 -->
        <el-divider></el-divider>
        <!-- 身体 -->
        <div id="bodydiv">
            <el-table :data="unitData" border stripe class="centered-table"> 
                <el-table-column prop="dd_sort" label="序号" ></el-table-column>
                <el-table-column prop="dd_label" label="名称"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="editUnit(scope.row)">修改</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteUnit(scope.row.dd_code)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
          <el-pagination class="pagination"
            @size-change="change"
            @current-change="Ymchange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]" 
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" 
            :total="rows">
          </el-pagination>
       <!-- 计量单位添加模态框 -->
       <el-dialog title="添加" :visible.sync="isAddUnitVisible" width="400px" :close-on-click-modal="false" class="qw">
        <el-form :model="Unitform" label-width="100px">
          <el-form-item label="值名称">
            <el-input v-model="Unitform.dd_label" autocomplete="off" placeholder="值名称"></el-input>
          </el-form-item>
        </el-form>
        <div>
          <span slot="footer" style="display: flex; justify-content: center;">
            <el-button @click="isAddUnitVisible = false"
              style="margin-right: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">取消</el-button>
            <el-button type="primary" @click="UnitsubmitForm"
              style="margin-left: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">确定</el-button>
          </span>
        </div>
      </el-dialog>

      <!-- 计量单位修改模态框 -->
      <el-dialog title="修改" :visible.sync="isEditUnitVisible" width="400px" :close-on-click-modal="false" class="qw">
        <el-form :model="editUnitForm" label-width="100px">
          <el-form-item label="客户编号">
            <el-input v-model="editUnitForm.dd_code" autocomplete="off" placeholder="客户编号" disabled></el-input>
          </el-form-item>
          <el-form-item label="值名称">
            <el-input v-model="editUnitForm.dd_label" autocomplete="off" placeholder="值名称"></el-input>
          </el-form-item>
          
        </el-form>
        <div>
          <span slot="footer" style="display: flex; justify-content: center;">
            <el-button @click="isEditUnitVisible = false"
              style="margin-right: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">取消</el-button>
            <el-button type="primary" @click="updateUnit"
              style="margin-left: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">修改</el-button>
          </span>
        </div>
      </el-dialog>
   
 </div>
</template>

<script>
import axios from 'axios';
import { format } from 'date-fns';
import { MessageBox } from 'element-ui';
import $http from '@/routers/base';
export default {
  
  data() {
    return {
      username:localStorage.getItem('username'),
      isAddUnitVisible: false, // 控制新增客户弹窗的显示状态
      isEditUnitVisible:false,
      currentPage: 1, //当前页
      pageSize: 5, //每页显示数
      rows: 0, //总行数
      unitData:[],
      Unitform:{
        dd_label:"",
      },
      editUnitForm:{
        dd_code:'',
        dd_label:"",
      },
    };
  },
  
  methods: {
    handleClick() {  
      alert('Span在Vue中被点击了！');  
    },
    // 显示新增计量单位弹窗
    UnitAddModal() {
      this.isAddUnitVisible = true;
    },
    
    //查询计量单位
    async getUnit() {
      const response = await $http.get('dict_data/Queryunit');
      this.unitData = response
      
    },
    //计量单位分页
    getUnit() {
          this.where="dd_type='type_unit'";
      // 向后端请求数据，并更新客户数据和总条数
       $http.get('dict_data/getUnitFenYe', {
        params: {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          where:this.where
       }
     }).then(res => {
            this.unitData =res.unitData;
            this.rows=res.rows;
     }).catch(error => {
        console.error('Error fetching client data: ', error);
     });
    },
     change: function(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.clientsData();
    },
    Ymchange: function(page) {
      this.currentPage = page;
      this.clientsData();
    },

    //计量单位添加
    async UnitsubmitForm() {
      if (this.submitUnitForm()) {
        
        $http.post('dict_data/clientAdd',{
              "dd_label":this.Unitform.dd_label,
              "dd_type":"type_unit",
              "dd_sort":0,
              "dd_create_by":this.username,
              "dd_create_time":format(new Date(), 'yyyy-MM-dd'),
              "dd_update_by":null,
              "dd_update_time":null,
              "dd_remark":"默认",
              "isDeleted":false
        }).then(response => {
            if (response) {
              this.isAddUnitVisible = false;
              this.getUnit();
              this.$message.success('添加成功！');
              this.Unitform.dd_label='';
            } else {
              console.log('新增客户数据：', response.data);
            }
          }).catch(error => {
            this.$message.error('添加失败：' + error.message);
            
          })
      }
    },

    //获取数据
    editUnit(row){
      
    
       this.isEditUnitVisible = true;

       this.$set(this.editUnitForm, 'dd_code', row.dd_code);
       this.$set(this.editUnitForm, 'dd_label', row.dd_label);
       this.$set(this.editUnitForm, 'dd_type', row.dd_type);
       this.$set(this.editUnitForm, 'dd_sort', row.dd_sort);
       this.$set(this.editUnitForm, 'dd_create_by', row.dd_create_by);
       this.$set(this.editUnitForm, 'dd_create_time', row.dd_create_time);
       this.$set(this.editUnitForm, 'dd_remark', row.dd_remark);
       this.$set(this.editUnitForm, 'isDeleted', row.isDeleted);
       
       // 设置修改人和修改时间字段
      this.$set(this.editUnitForm, 'dd_update_by', this.username);
      //npm install date-fns

      const formattedDate = format(new Date(), 'yyyy-MM-dd');
      this.$set(this.editUnitForm, 'dd_update_time', formattedDate);
    },
     //计量单位修改
     async updateUnit() {
      if (this.UnitEditForm()) {
        $http.put('dict_data/unitUpdate', this.editUnitForm)
          .then(response => {
            if (response) {
              this.$message.success('修改成功！');
              this.isEditUnitVisible = false;
              this.getUnit();
              
            } else {
              this.$message.error('修改失败！请重试！');
            }
          }).catch(error => {
            this.$message.error('修改失败：' + error.message);
          })
      }
    },
    submitUnitForm(){
      let dd_label = this.Unitform.dd_label.trim() !== '';
      if (!dd_label) {
        this.$message.error('名字不能为空！');
        return false;
      }
      return true;
    },
   
    UnitEditForm(){
      let dd_label = this.editUnitForm.dd_label.trim() !== '';
      if (!dd_label) {
        this.$message.error('名字不能为空！');
        return false;
      }
      return true;
    },
    async deleteUnit(dd_code){
      console.log(dd_code);
      MessageBox.confirm('确认删除删除该条记录吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        axios.delete(`dict_data/unitDelete/${dd_code}`)
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.getUnit();
          }).catch(error=>{
            this.$message.error('删除失败：'+error.message)
          })
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '管理员取消了删除,删除无效哦！'
          })
        })
    },
    
  },
  mounted() {
    this.getUnit();
  },
};
</script>

<style scoped src="../CSS/Warning.css"></style>
<style scoped>
#desDiv{
    width: 100%;
    height: 100%;
}
#sale{
    float:right;
    bottom: 0;
    right: 100px;
   
}
</style>